package com.timk.goserver.client.ui.screens;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.timk.goserver.client.model.ClientUserInfo;
import com.timk.goserver.client.services.NoSessionException;
import com.timk.goserver.client.ui.widgets.RankGraphLink;
import com.timk.goserver.client.ui.widgets.StatusLabel;

/**
 * Panel with user details
 * @author TKington
 *
 */
public class UserInfoPanel extends Composite {
	final String username;		// NOPMD - explicit scoping
	final StatusLabel status;	// NOPMD - explicit scoping
	private final Label nameLabel;
	private final HTML rankHTML;
	
	/**
	 * Creates a UserInfoPanel
	 * 
	 * @param username the user to display info for
	 */
	public UserInfoPanel(String username) {
		this.username = username;
		VerticalPanel panel = new VerticalPanel();
		
		status = new StatusLabel();
		panel.add(status);
		
		HorizontalPanel namePanel = new HorizontalPanel();
		namePanel.add(new Label("Name:"));
		
		nameLabel = new Label();
		namePanel.add(nameLabel);
		
		panel.add(namePanel);
		
		HorizontalPanel rankPanel = new HorizontalPanel();
		rankPanel.add(new Label("Rank:"));
		
		rankHTML = new RankGraphLink(username);
		rankPanel.add(rankHTML);
		
		panel.add(rankPanel);
		
		initWidget(panel);
		
		refresh();
	}
	
	/**
	 * Reloads the user's info
	 */
	public final void refresh() {	
		MainPanel.userService.getUser(username, new AsyncCallback() {
			public void onSuccess(Object result) {
				populateUserInfo((ClientUserInfo)result);
			}
			
			public void onFailure(Throwable caught) {
				if(caught instanceof NoSessionException) {
					MainPanel.sessionExpired(caught.getMessage());
					return;
				}
				
				status.setError("Error loading user");	
			}
		});
	}
	
	final void populateUserInfo(ClientUserInfo user) {
		status.clear();
		
		nameLabel.setText(user.getFullname());
		rankHTML.setHTML("<u>" + user.getRank() + "</u>");
	}
}
